package com.example.permission.controller;

import com.example.permission.entity.Role;
import com.example.permission.service.RoleService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.List;

@WebServlet("/roles")
public class RoleController extends HttpServlet {

    private RoleService roleService;

    @Override
    public void init() throws ServletException {
        roleService = (RoleService) getServletContext().getAttribute("roleService");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String action = request.getParameter("action");

        if ("detail".equals(action)) {
            // 任务二：查询特定角色及其权限
            String roleIdStr = request.getParameter("roleId");
            String roleName = request.getParameter("roleName");

            Role role = null;
            if (roleIdStr != null && !roleIdStr.trim().isEmpty()) {
                Long roleId = Long.parseLong(roleIdStr);
                role = roleService.getRoleWithMenusById(roleId);
            } else if (roleName != null && !roleName.trim().isEmpty()) {
                role = roleService.getRoleWithMenusByName(roleName);
            }

            request.setAttribute("role", role);
            request.getRequestDispatcher("/views/role-detail.jsp").forward(request, response);
            return;
        }

        // 默认显示角色列表（分页）
        String pageStr = request.getParameter("page");
        int page = (pageStr != null) ? Integer.parseInt(pageStr) : 1;
        int pageSize = 10;

        List<Role> roles = roleService.getRolesByPage(page, pageSize);
        int totalCount = roleService.getRoleCount();
        int totalPages = (int) Math.ceil((double) totalCount / pageSize);

        request.setAttribute("roles", roles);
        request.setAttribute("currentPage", page);
        request.setAttribute("totalPages", totalPages);
        request.getRequestDispatcher("/views/role-list.jsp").forward(request, response);
    }
}